<!DOCTYPE HTML>
<html>
  <head>

    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
    <meta name="apple-mobile-web-app-capable" content="yes" />
<!--
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
-->
   <title>20th century reanalysis demo</title>

    <link href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/mobile/themes/iphone/iphone.css" rel="stylesheet"></link>
    <link href="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojox/mobile/themes/domButtons.css" rel="stylesheet"></link>
 
<!--[if IE]>
  <script src="http://danvk.org/dygraphs/excanvas.js"></script>
<![endif]-->
   <script src="http://danvk.org/dygraphs/dygraph-combined.js"></script> 
   <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
      djConfig = { parseOnLoad:true, isDebug:false };
    </script>
    <script src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('dojo', '1.6');  
    </script>
<script language="JavaScript" type="text/javascript">

      //dojo.require("dojo.parser"); // Use the lightweight parser.
      dojo.require("dojox.mobile");
      dojo.require("dojox.mobile.parser");
      dojo.requireIf(!dojo.isWebKit, "dojox.mobile.compat");
      dojo.require("dojo.io.script");
      dojo.require("dojo.DeferredList");
      dojo.require("dojox.mobile.TabBar");
      dojo.require("dojox.mobile.app.TextBox");
      //dojo.require("dojox.mobile.ScrollableView");

      dojo.addOnLoad(function(){
        buildList();
        initmap();
      });

/*
      // Use the lightweight parser.
      dojo.require("dojox.mobile");
      dojo.require("dojox.mobile.parser");
      dojo.require("dojo.io.script");
      dojo.require("dojo.DeferredList");
      dojo.require("dojox.mobile.TabBar");
      dojo.require("dojox.mobile.app.TextBox");
      dojo.requireIf(!dojo.isWebKit, "dojox.mobile.compat");
      dojo.addOnLoad(function(){
        initmap();
      });
*/
   
  var map;
  var graphhi;  // The Dygraph

function initmap() {
    var myOptions = {
      zoom: 2,
      center: new google.maps.LatLng(40, 20),
      mapTypeControl: false, 
      mapTypeId: google.maps.MapTypeId.TERRAIN,
      streetViewControl: false
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);
      google.maps.event.addListener(map, 'click', function(event) {
      fetchDataByPosn(event.latLng);
    }); 

   var wxMapOptions = {
    map: map,
    name: "Wx",
    minZoom: 3,
    maxZoom: 10
   }
   var wxstyle = [
    {featureType:"all",stylers:[{hue: 000000},{saturation: -10},{lightness: 30}]},
    {featureType:"road",elementType:"all",stylers:[{visibility:"off"}]},
    {featureType:"administrative",elementType:"labels",stylers:[{visibility:"on"}]}];
   var wxMapType =  new google.maps.StyledMapType(wxstyle,wxMapOptions);
   map.mapTypes.set('wx', wxMapType);
   map.setMapTypeId('wx');
   return 0;
 }

var params = [{q:"prate_mon_mean",en:"monthly rainfall",u:"mm",spr:0},
{q:"sprd_prate_mon_mean",en:"monthly rainfall spread",u:"mm",spr:1},
{q:"air_2m_mon_mean",en:"month mean temperature 2m",u:"C",spr:0},
{q:"sprd_air_2m_mon_mean",en:"month mean temperature 2m spread",u:"C",spr:1},
{q:"tmin_2m_mon_mean",en:"month mean min temp 2m",u:"C",spr:0},
{q:"tmax_2m_mon_mean",en:"month mean max temp 2m",u:"C",spr:0},
{q:"wspd_10m_mon_mean",en:"month mean wind speed 10m",u:"m/s",spr:0},
{q:"sprd_wspd_10m_mon_mean",en:"month mean wind speed spread",u:"m/s",spr:1},
{q:"ncep_prate_sfc_mon_mean",en:"NCEP monthly rainfall",u:"mm",spr:0},
{q:"ncep_air_2m_mon_mean",en:"NCEP month mean temp 2m",u:"C",spr:0}];

var paramSelection = [params[0],params[2]];
var locationSelection = {x:-1,y:-1};
var yearStart = 1871;
var yearEnd = 2011;


function plotData(arr){
  // first need to merge the arrays

  // 'Temperature':{axis:{yAxisLabelFormatter:function(x){return x}}}

  var combined = new Array();
  var settings;

  if(paramSelection[1].spr == 1){
    for(var i in arr[0]){
      var d = new Date(arr[0][i][0]);
      var v = arr[0][i][1];
      var e = arr[1][i][1]/2.0;
      var lo = v-e;
      var hi = v+e;
      if((paramSelection[1].u == "mm")&&(lo<0)){lo=0;hi=2*e;}
      combined.push([d,[lo,v,hi]]);
    }
    settings = {labels:["Date",paramSelection[0].en],customBars:true,errorBars:true};
  }
  else{
    for(var i in arr[0]){
      var d = new Date(arr[0][i][0]);
      combined.push([d,arr[0][i][1],arr[1][i][1]]);
      }
    settings = {labels:["Date",paramSelection[0].en,paramSelection[1].en]};
    // If parameters have different units, then give them separate scales 
    if( paramSelection[0].u != paramSelection[1].u ){
        settings[paramSelection[1].en] = {axis:{}};
    }
  }
  
  graphhi = new Dygraph(dojo.byId("graphdivhi"), combined, settings);
}

function  showAttrs(res){
   if(res[0][0]){
     dojo.byId("attrtxt").innerHTML = "<a href=\"20cr-about.html\">" +
     res[0][1].attributes.NC_GLOBAL.title +"<\a>";
   }
}

var okToClick = true;

function lfnn(xy){
      var yr0 = dojo.byId("tbyr0").value;
      var yr1 = dojo.byId("tbyr1").value;
      var mo = dojo.byId("tbmo").value;
      locationSelection = xy;
      dojo.byId("dl_x").innerHTML = locationSelection.x;
      dojo.byId("dl_y").innerHTML = locationSelection.y;

      var p1 = {quantity:paramSelection[0].q};
      var fetch_param1 =  dojo.io.script.get({
      url:"http://saunby.net/cgi-bin/py/series20cr.py", 
      content:{yr0:yr0,yr1:yr1,x:xy.x,y:xy.y,q:p1.quantity,mo:mo},
      callbackParamName: "callback", handleAs:"json"});
      var p2 = {quantity:paramSelection[1].q};
      var fetch_param2 =  dojo.io.script.get({
      url:"http://saunby.net/cgi-bin/py/series20cr.py", 
      content:{yr0:yr0,yr1:yr1,x:xy.x,y:xy.y,q:p2.quantity,mo:mo},
      callbackParamName: "callback", handleAs:"json"});
      
      var defs = new dojo.DeferredList([fetch_param1,fetch_param2]);
      
      // defs.then() sets the function called when all calls in the deferred list have
      // returned.  See http://dojotoolkit.org/documentation/tutorials/1.6/deferreds/
      defs.then(function(res){
      okToClick = true;
      plotData([res[0][1].data,res[1][1].data]);
      showAttrs(res);
      });
}
      
function efn(msg){
      alert(msg);
      okToClick = true;
}

function coords20cr(vals) {
   dojo.io.script.get({
        //Cross domain works - use this URL
        url: "http://saunby.net/cgi-bin/py/coords20cr.py",
	content:{lat:vals.latlng.lat(),lng:vals.latlng.lng()},
        callbackParamName: "callback",
        load: vals.load,
        error: vals.error});
}

function replot(){
      // get position
      var posntxt = dojo.byId("tblocn").value;
      var n = posntxt.match(/\-?\d+\.?\d*N/)[0].slice(0,-1);
      var e = posntxt.match(/\-?\d+\.?\d*E/)[0].slice(0,-1);
      var latlng = new google.maps.LatLng(n,e);
      fetchDataByPosn(latlng);
}

function showPosn(latlng){
      dojo.byId("tblocn").value = latlng.lat().toFixed(2) + "N," + latlng.lng().toFixed(2) + "E";
      dojo.byId("graphdivhi").innerHTML = "<p>" + paramSelection[0].en + "<br>" +   paramSelection[1].en + "</p>";
      dojo.byId("attrtxt").innerHTML = "";
}

var marker = null;


// Map click listener
function fetchDataByPosn(latlng) {

   if( !okToClick ){
     //alert("sorry you can't get another graph right now");
     return;					      
   }

   okToClick = false;					      
   mylatlng = latlng;
   showPosn(latlng);

   if(marker){marker.setMap(null);}
   marker = new google.maps.Marker({
            map: map,
            title:  latlng.lat() + "N," + latlng.lng() + "E",
            position: latlng
        });
   coords20cr({latlng:mylatlng,load:lfnn,error:efn});
   return 0;
}

function mytest() {
      var yr0 = dojo.byId("tbyr0").value;
      var yr1 = dojo.byId("tbyr1").value;
      alert("from " + yr0 + " to " + yr1);
}

function refresh() {
      //var mapdiv = document.getElementById("map");
      //mapdiv.style.width = '100%';
      //mapdiv.style.height = '400px';
      google.maps.event.trigger(map, "resize");
}

var selectedP;
var selectedPId;



function updateInfo(){
     dojo.byId("graphdivhi").innerHTML = "<p>" + paramSelection[0].en + "<br>" +   paramSelection[1].en + "</p>";

      yearStart = dojo.byId("tbyr0").value; 
      yearEnd = dojo.byId("tbyr1").value;

      dojo.byId("dl_yr0").innerHTML = yearStart;
      dojo.byId("dl_yr1").innerHTML = yearEnd;
      dojo.byId("dl_q0").innerHTML = paramSelection[0].q;
      dojo.byId("dl_q1").innerHTML = paramSelection[1].q;
      dojo.byId("dl_x").innerHTML = locationSelection.x;
      dojo.byId("dl_y").innerHTML = locationSelection.y;
}


function selSet(d){
      paramSelection[ selectedP ] = d;
      selectedPId.set("RightText", d.en);

      updateInfo();
}

function selP(data){
      n = data[0];
      selectedPId = data[1];
      selectedP = n-1;
}

function buildList(){
      dojo.byId("tbyr0").value = yearStart; 
      dojo.byId("tbyr1").value = yearEnd;

      param1 = new dojox.mobile.ListItem({label:"parameter 1",rightText:paramSelection[0].en,moveTo:"selectionView"}).placeAt(dojo.byId("paramList"), "last");
      dojo.connect(param1.containerNode, "onclick", dojo.hitch(null, selP, [1, param1])); 
      param2 = new dojox.mobile.ListItem({label:"parameter 2",rightText:paramSelection[1].en,moveTo:"selectionView"}).placeAt(dojo.byId("paramList"), "last");
      dojo.connect(param2.containerNode, "onclick", dojo.hitch(null, selP, [2, param2])); 
      for( var li in params){ 
        var item = new dojox.mobile.ListItem({label:params[li].en,moveTo:"paramView"});
        dojo.connect(item.containerNode, "onclick", dojo.hitch(null, selSet, params[li]));  
        item.placeAt(dojo.byId("selList"), "last");
      }
      updateInfo();
}   

function download(){
  var dlURL = "?yr0=" + yearStart + "&yr1=" + yearEnd + "&mo=0" + "&q0=" + paramSelection[0].q + "&q1=" + paramSelection[1].q +
  "&x=" +  locationSelection.x + "&y=" + locationSelection.y;
  window.location = "http://map.wepoco.com/getcsv" + dlURL;
}



</script>
  </head>
  <body>
    <div id="graphView" dojoType="dojox.mobile.View" selected="true">
      <h1 dojoType="dojox.mobile.Heading" label="20th century reanalysis demo">
        <div dojoType="dojox.mobile.ToolBarButton" label="Download" moveTo="downloadView" style="float:right;"></div>
	<div dojoType="dojox.mobile.ToolBarButton" label="Parameters" moveTo="paramView" style="float:right;"></div>
      </h1>

      <div dojoType="dojox.mobile.RoundRect"> 
	<label for="tbyr0">First year</label> 
	<input dojoType="dojox.mobile.app.TextBox" id="tbyr0" name="yr0" size="4" value="" onchange="updateInfo()"></input>
	<label for="tbyr1">Last year</label> 
	<input dojoType="dojox.mobile.app.TextBox" id="tbyr1" name="yr1" size="4" value="" onchange="updateInfo()"></input>
	<label for="tbmo">Month</label>
	<input dojoType="dojox.mobile.app.TextBox" id="tbmo" name="mo" size="2" value=""></input>
	<label for="tblocn">Location</label>
	<input dojoType="dojox.mobile.app.TextBox" id="tblocn" name="locn" value="0N,0E"></input>
        <button dojoType="dojox.mobile.Button" onClick="replot()">Plot</button>
	<div id="graphdivhi" style="width:95%;height:220px;" ></div>
        <p id="attrtxt"></p>
      </div>
      <div dojoType="dojox.mobile.RoundRect"> 
        <div id="map" style="width:100%;height:400px;"></div>
      </div>
    </div>
    <div id="paramView" dojoType="dojox.mobile.View">
      <h1 dojoType="dojox.mobile.Heading" label="Parameters" back="graph" moveTo="graphView" ></h1>
      <div dojoType="dojox.mobile.RoundRect"><ul id="paramList"></ul></div> 
    </div>
   <div id="selectionView" dojoType="dojox.mobile.View">
      <h1 dojoType="dojox.mobile.Heading" label="Parameters" back="cancel" moveTo="paramView" ></h1>
      <div dojoType="dojox.mobile.RoundRectList"><ul id="selList"></ul></div> 
    </div>
   <div id="downloadView" dojoType="dojox.mobile.View">
      <h1 dojoType="dojox.mobile.Heading" label="Download" back="graph" moveTo="graphView" ></h1>
         <div dojoType="dojox.mobile.RoundRect"> 
	  Download data series in spreadsheet compatible format 
	  <p>
	  Date range: <span id="dl_yr0"></span>-<span id="dl_yr1"></span><br>
	  Grid cell: <span id="dl_x"></span>,<span id="dl_y"></span><br>
	  Parameter 1: <span id="dl_q0"></span><br>
	  Parameter 2: <span id="dl_q1"></span><br>
          </p>
	  <p>Return to graph to change the selection.</p>
	  <button dojoType="dojox.mobile.Button" onClick="download()">Download as CSV</button>
	 </div>
    </div>
  </body>
</html>
